library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights2 / N_ind) 


########### Regression analyses

country_df <- data.frame(country_abb = c("NL", "PL", "DE", "ES", "SE", "GB", "FR", "IT", "GR"),
                         country = c("Netherlands", "Poland", "Germany", "Spain", 
                                     "Sweden", "United Kingdom", "France", "Italy", 
                                     "Greece"), 
                         coef = NA, 
                         se = NA, 
                         pvalue = NA)


models <- list()

for(i in 1:nrow(country_df)){
  
  country <- country_df$country_abb[i]
  
  mod <- feols(close_num ~ feeling_toward | meta_UUID, survey_long %>% filter(dem_country_code == country), 
               weights = survey_long$weights[survey_long$dem_country_code == country])
  country_df$coef[i] <- mod$coefficients
  country_df$se[i] <- mod$se[1]
  country_df$pvalue[i] <- as.character(round(mod$coeftable$`Pr(>|t|)`, 3)) 
  
  models[[i]] <- mod
  
  print(i)
}

country_df$pvalue <- ifelse(country_df$pvalue == "0", "0.000", country_df$pvalue)
country_df$pvalue <- paste0("(", country_df$pvalue, ")")
country_df$country <- factor(country_df$country,
                             levels = c("Greece", "United Kingdom", "Netherlands", 
                                        "Poland", "France",  "Sweden", "Italy",
                                        "Germany", "Spain"))

######### Figure A1 #########

pd <- position_dodge(0.5)

regs <- ggplot(country_df, aes(x = country, ymin = coef - se*1.96, y = coef, ymax = coef + se*1.96)) + 
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(width = 0, position = pd) + 
  ylim(c(0, 0.45)) +
  xlab("") + 
  geom_text(aes(label = pvalue), nudge_y = 0.06, inherit.aes = T, size = 2.5) +
  ylab("Feeling coefficient") +
  coord_flip() +
  theme_bw()
regs

ggsave("figures/FigureA1.jpeg", plot = regs,
       height = 4, width = 4, dpi = 600)



######### Table A6 #########

options("modelsummary_format_numeric_latex" = "plain")
names(models) = country_df$country_abb
models <- models[order(names(models))]

tab <- modelsummary(models, stars = TRUE,
             coef_rename = c("feeling_toward" = "Feeling", 
                             "meta_UUID" = "Individual-FE"),
             coef_omit = c("(Intercept)"),
             gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors", 
             statistic = "p.value") %>%
  add_header_above(c(" " = 1, "DV: Social distance (1-7)"= 9), line = T, italic = F)
kableExtra::save_kable(tab, file = "tables/TableA6.html")
